package rhinestone.Model;

import java.util.HashMap;
import java.io.Serializable;

/**
 * The container of all customers.
 *
 * @author Group 2
 * @version 2010.12.16
 */
public class CustomerContainer implements Serializable {
	private HashMap<String, Customer> customers;
	private static CustomerContainer instance;
	private boolean changed;

	/**
	 * Private constructor, which initializes instance variables.
	 */
	private CustomerContainer() {
		customers = new HashMap<String, Customer>();
		changed = false;
	}

	/**
	 * Singleton pattern.
	 *
	 * @return The object of this container.
	 */
	public static CustomerContainer getInstance() {
		if(instance == null)
			instance = new CustomerContainer();
		return instance;
	}

	/**
	 * Adds a customer to the database.
	 * Also sets the containers state as changed, so before exiting
	 * the program, this container will be serialized.
	 *
	 * @param customer The customer to be added.
	 */
	public void addCustomer(Customer customer) {
		if(getCustomer(customer.getCpr()) == null) {
			customers.put(customer.getCpr(), customer);
			changed = true;
		}
		else
			System.err.println("Customer with CPR " + customer.getCpr() + " already exists.");
	}

	/**
	 * Finds and return the customer with provided CPR.
	 *
	 * @param cpr CPR of the customer.
	 * @return The customer (null if not found).
	 */
	public Customer getCustomer(String cpr) {
		return customers.get(cpr);
	}

	/**
	 * Deletes the customer from database.
	 * Also it changes the status of container as changed,
	 * so before exiting the program, this container will be serialized.
	 *
	 * @param cpr
	 * @return
	 */
	public Customer deleteCustomer(String cpr) {
		changed = true;
		return customers.remove(cpr);
	}

	/**
	 * Self talking methods. Changed setter and getter.
	 */
	public void setChanged(boolean changed) {
		this.changed = changed;
	}
	public boolean isChanged() {
		return changed;
	}
}